#!/bin/bash 

# add scripts to path
export PATH="/workspace/tools/bin:/build/bin:$PATH"

echo "SDK version $(cat /etc/sdk_version)"

# set GPG home
if [ -d "/workspace/gpg-keys/.gnupg" ]; then
    echo "Setting GPG home..."
    export GNUPGHOME="/workspace/gpg-keys/.gnupg"
fi

# add workspace bin folder if it exists
WSBIN="/workspace/bin"
if [ -d "$WSBIN" ]; then
    echo "Adding '/build/workspace/bin' to PATH..."    
    export PATH="/build/workspace/bin:$PATH"
fi

# source identity if it exists
IDENTITY="/build/identity/env"
if [ -f "$IDENTITY" ]; then
    echo "Sourcing '${IDENTITY}'..."    
    source $IDENTITY
else
    IDENTITY="/workspace/identity/env"
    if [ -f "$IDENTITY" ]; then
        echo "Sourcing '${IDENTITY}'..."    
        source $IDENTITY
    fi
fi

# source workspace env, if it exists
ENV="/workspace/.env"
if [ -f "$ENV" ]; then
    echo "Sourcing '${ENV}'..."    
    source $ENV
fi

# source user env, if it exists
ENV="/workspace/tools/user_config/.env"
if [ -f "$ENV" ]; then
    echo "Sourcing '${ENV}'..."    
    source $ENV
fi

if [ ! -d "/tmp/build/images" ]; then
    bash -c "overlay_mount /build/images"
fi

source /build/venv/bin/activate


# Run user setup
if [ -d "/workspace/tools/user_config" ]; then
    echo "Running user extensions..."
    if [ -x "/workspace/tools/user_config/user_extensions" ]; then
        echo "Running user extensions script..."
        /workspace/tools/user_config/user_extensions
    fi
fi
